package com.googlecode.imanager.swing.form;

import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.AbstractButton;

import com.googlecode.imanager.client.bridge.form.IInputCheck;
import com.googlecode.imanager.client.form.CheckGroup;
import com.googlecode.imanager.client.form.InputCheck;
import com.googlecode.imanager.core.base.BridgeApplication;

/**
 * @author wellsantos@wellsantos.com
 * @since 0.01
 */
public abstract class SwingInputCheck extends SwingInputControl implements IInputCheck {

    public SwingInputCheck(BridgeApplication bridge, InputCheck source) {
        super(bridge, source);
        getTarget().setBackground(null);
    }

    @Override
    protected abstract AbstractButton createTarget();

    @Override
    public AbstractButton getTarget(){
        return (AbstractButton) target;
    }
    
    @Override
    public InputCheck getSource() {
        return (InputCheck) source;
    }

    @Override
    protected void doAttachEvents() {
        super.doAttachEvents();
        getTarget().addItemListener(new ItemListener() {
            
            @Override
            public void itemStateChanged(ItemEvent e) {
                synchronized (TREE_LOCK) {
                    if (!isDropped()){
                        startFireUIEvent();
                        try {
                            getSource().setChecked(getTarget().isSelected());
                        } catch (Exception ex) {
                            processException(ex);
                        } finally {
                            endFireUIEvent();
                        }
                    }
                }
            }
            
        });
    }

    @Override
    public void setChecked(Boolean checked) {
        getTarget().setSelected(checked == null ? false : checked);
    }

    @Override
    public void setText(String text) {
        getTarget().setText(text);
    }

    @Override
    public void setGroup(CheckGroup group) {
        // nothing to do
    }

}
